package com.alex.core.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import feign.Logger;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Configuration
public class FeignConfiguration {
    @Bean
    public Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

    @Bean
    public HttpMessageConverters messageConverters() {
        Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();

        //序列化  Object --> Json
        //空值不包含不序列化
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        //数字也加引号
        builder.featuresToEnable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
        builder.featuresToEnable(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS);

        //反序列化 Json --> Object
        //属性不存在，不抛出异常
        builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //大小写脱敏
        builder.featuresToDisable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);

        builder.featuresToEnable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        builder.featuresToEnable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);

        return new HttpMessageConverters(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}
